package cn.tedu.csmall.passport.security;

import cn.tedu.csmall.passport.mapper.AdminMapper;
import cn.tedu.csmall.passport.pojo.vo.AdminLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private AdminMapper adminMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("Security根据用户名{}查询用户详情",s);

        AdminLoginVO admin = adminMapper.getByUsername(s);

        if (admin != null) {
            log.debug("查询到匹配的管理员信息:{}",admin);
            List<String> permissions = admin.getPermissions();

            UserDetails userDetails =User.builder()
                    .username(admin.getUsername())
                    .password(admin.getPassword())
                    .disabled(false)//账号是是否禁用
                    .accountLocked(false)//账号是否锁定
                    .credentialsExpired(false)//认证是否过期
                    .authorities(permissions.toArray(new String[] {}))//【必须】此账号的权限信息
                    .build();
            log.debug("即将向Security返回UserDetails:{}",userDetails);
            return userDetails;
        }
        log.error("没有查询到匹配的管理员信息");
        return null;
    }
}
